<?php

namespace app\wechat\models;

use cm;
use Yii;
use yii\helpers\Url;
use ReflectionClass;
use ReflectionMethod;
use yii\base\Model;

class MainModel extends Model
{
    public $openid;
    public $config;
    public $access_token;
    public $token;

    /*
    *获取授权code的接口地址
    */
    public function actionCode(){
        $callback = 'http://' . $_SERVER['SERVER_NAME'] . ($_SERVER["SERVER_PORT"] == 80 ? '' : ':' . $_SERVER["SERVER_PORT"]);
        $type = (int)Cm::$req->post('type', ['null', 'empty', 'default' => 0]);
        
        if($type == 1){
            $callback .= '/home';
        }elseif($type == 2){
            $callback .= '/inspector/#/login';
        }else{
            Cm::$res->error("获取授权回调类型不正确");
        }
        $oauth2Url = Cm::$libs->wechat->OauthApi->getOauthRedirect($callback, 'STATE', 'snsapi_userinfo');
        Cm::$res->susess(['url'=>$oauth2Url]);
    }

    /*
    * 首页授权获取token
    */
    public function actionToken(){
        $code = Cm::$req->post('code', ['null', 'empty', 'default' => '']);
        if(empty($code)){
            Cm::$res->error("参数错误,没有获取到CODE");
        }
        $res = Cm::$libs->wechat->OauthApi->getOauthAccessToken();
        $this->openid = isset($res['openid']) ? $res['openid'] : '';
        $this->access_token = isset($res['access_token']) ? $res['access_token'] : '';
        if (empty($this->openid)){
            Cm::$res->error("获取openid失败", [], false);
        }
        define('WX_OPENDID', $this->openid);
        $this->initUser();
        Cm::$res->susess(['token'=>$this->token]);
    }

    /*
    *获取用户信息新增或更新
    */
    private function initUser(){
    	$userInfoSql = "SELECT * FROM user WHERE openid='{$this->openid}'";
        $userInfo = Cm::$db->one($userInfoSql);
        $time = time();
        $timestr = date("Y-m-d H:i:s",$time);
        $this->token = md5($this->openid . time() . rand(10000, 99999));
        $expires_time = $time+60*60*24*30;
        $wxUser = Cm::$libs->wechat->OauthApi->getUserInfo($this->access_token, $this->openid);
        if(empty($userInfo)){
            $data = [
                'head_img' => isset($wxUser['headimgurl']) ? $wxUser['headimgurl'] : '',
                'nickname' => isset($wxUser['nickname']) ? $wxUser['nickname'] : '',
                'sex' => isset($wxUser['sex']) ? $wxUser['sex'] : '',
                'openid' => $this->openid,
                'token' => $this->token,
                'session_key' => $this->access_token, 
                'expires_time' => $expires_time,
                'status' => 1,
                'updatetime' => $timestr,
                'addtime' => $timestr
            ];
            $userID = Cm::$db->insert("user", $data);
            if($userID){
                $data['id'] = $userID;
            }else{
                Cm::$res->error("授权获取失败");
            }
            $userInfo = $data;
        }else{
            $data = [
                'token' => $this->token,
                'session_key' => $this->access_token, 
                'expires_time' => $expires_time,
                'updatetime' => $timestr
            ];
            Cm::$db->update("user", $data, "id={$userInfo['id']}");
            $userInfo['token'] = $this->token;
            $userInfo['session_key'] = $this->access_token;
            $userInfo['expires_time'] = $expires_time;
            $userInfo['updatetime'] = $timestr;
        }
        Cm::$app->user->setIdentity($userInfo);
    }
}